<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\model\Swiper as SwiperModel;
use app\common\controller\Backend;
use think\Request;

class Swiper extends Backend
{
    //轮播图列表
    public function index()
    {
        $swiperList = SwiperModel::select();
        return $this->fetch('swiper/index', ['swiperList' => $swiperList]);
    }

    //轮播图编辑
    public function edit(Request $request)
    {
        $swiper = SwiperModel::findOrEmpty($request->get('id', 0));
        return $this->fetch('swiper/edit', [
            'swiper' => $swiper
        ]);
    }

    //轮播图保存
    public function save(Request $request)
    {
        try {
            $data = $request->post();

            if (!empty($data['image-data'])) {
                $data['image'] = $this->uploadImageData($data['image-data']);
                unset($data['image-data']);
            }

            if (empty($data['id'])) {
                SwiperModel::create($data);
            } else {
                SwiperModel::update($data);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->redirect('index');
    }

    //轮播图删除
    public function delete(Request $request)
    {
        try {
            SwiperModel::destroy($request->get('id'));
        } catch (\Exception $e) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }
}
